package com.report.reportserver.interceptor;

import com.report.reportserver.config.security.JwtTokenUtils;
import com.report.reportserver.model.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ ClassName: LoginInterceptor
 * @ Description：拦截器
 * @ Modified By：
 * @ Version:
 * @ Author     ：LiYing
 * @ Date       ：Created in 21:43 2022/3/7
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        //Authorization参数是前台放在headler中的key
        String token = request.getHeader("Authorization");

        if(token != null){
            User user = JwtTokenUtils.validationToken(token);
            if(user != null){
                return true;
            }
        }
        System.out.println("token认证失败，请登录...");//跳转登录
        response.sendRedirect(request.getContextPath() + "/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
